<template>
  <div id="brushQuestion">
    <div class="flexarea">
      <!-- 左边题目编号区 -->
      <transition name="slider-fade">
        <div
          class="left"
          v-if="slider_flag"
          :key="1"
        >
          <ul class="l-top">
            <li><a href="javascript:;"></a><span>当前</span></li>
            <li><a href="javascript:;"></a><span>未答</span></li>
            <li><a href="javascript:;"></a><span>已答</span></li>
            <li><a href="javascript:;"></a><span>标记</span></li>
          </ul>
          <div class="l-bottom">
            <!-- 单项选择题部分 -->
            <div class="item">
              <p class="section-title">单项选择题部分</p>
              <ul>
                <li
                  v-for="(item, index1) in paginatedMulti"
                  :key="getGlobalIndex('multi', index1)"
                >
                  <a
                    href="javascript:;"
                    @click="goToMulti(getGlobalIndex('multi', index1))"
                    :class="{
  correct: isAnswerCorrect('multi', item.questionDetail.rightAnswer, radio[getGlobalIndex('multi', index1)]),
  wrong: radio[getGlobalIndex('multi', index1)] !== undefined && 
         !isAnswerCorrect('multi', item.questionDetail.rightAnswer, radio[getGlobalIndex('multi', index1)])
  }"
                  >
                    <span :class="{ mark: item.isMark === true }"></span>
                    {{ getGlobalIndex('multi', index1) + 1 }}
                  </a>
                </li>
              </ul>
              <div
                class="pagination"
                v-if="totalPagesMulti > 1"
              >
                <button
                  @click="prevPage('multi')"
                  :disabled="currentPageMulti === 1"
                >上一页</button>
                <span>第 {{ currentPageMulti }} 页，共 {{ totalPagesMulti }} 页</span>
                <button
                  @click="nextPage('multi')"
                  :disabled="currentPageMulti === totalPagesMulti"
                >下一页</button>
              </div>
            </div>

            <!-- 多项选择题部分 -->
            <div class="item">
              <p class="section-title">多项选择题部分</p>
              <ul>
                <li
                  v-for="(item, index2) in paginatedFill"
                  :key="getGlobalIndex('fill', index2)"
                >
                  <a
                    href="javascript:;"
                    @click="goToFill(getGlobalIndex('fill', index2))"
                    :class="{
  correct: submittedFill[getGlobalIndex('fill', index2)] && 
           isAnswerCorrect('fill', item.questionDetail.answer, fillAnswer[getGlobalIndex('fill', index2)]),
  wrong: submittedFill[getGlobalIndex('fill', index2)] && 
         !isAnswerCorrect('fill', item.questionDetail.answer, fillAnswer[getGlobalIndex('fill', index2)])
}"
                  >
                    <span :class="{ mark: item.isMark === true }"></span>
                    {{ getGlobalIndex('fill', index2) + 1 }}
                  </a>
                </li>
              </ul>
              <div
                class="pagination"
                v-if="totalPagesFill > 1"
              >
                <button
                  @click="prevPage('fill')"
                  :disabled="currentPageFill === 1"
                >上一页</button>
                <span>第 {{ currentPageFill }} 页，共 {{ totalPagesFill }} 页</span>
                <button
                  @click="nextPage('fill')"
                  :disabled="currentPageFill === totalPagesFill"
                >下一页</button>
              </div>
            </div>

            <!-- 判断题部分 -->
            <div class="item">
              <p class="section-title">判断题部分</p>
              <ul>
                <li
                  v-for="(item, index3) in paginatedJudge"
                  :key="getGlobalIndex('judge', index3)"
                >
                  <a
                    href="javascript:;"
                    @click="goToJudge(getGlobalIndex('judge', index3))"
                   :class="{
  correct: isAnswerCorrect('judge', item.questionDetail.rightAnswer, judgeAnswer[getGlobalIndex('judge', index3)]),
  wrong: judgeAnswer[getGlobalIndex('judge', index3)] !== undefined && 
         !isAnswerCorrect('judge', item.questionDetail.rightAnswer, judgeAnswer[getGlobalIndex('judge', index3)])
}"
                  >
                    <span :class="{ mark: item.isMark === true }"></span>
                    {{ getGlobalIndex('judge', index3) + 1 }}
                  </a>
                </li>
              </ul>
              <div
                class="pagination"
                v-if="totalPagesJudge > 1"
              >
                <button
                  @click="prevPage('judge')"
                  :disabled="currentPageJudge === 1"
                >上一页</button>
                <span>第 {{ currentPageJudge }} 页，共 {{ totalPagesJudge }} 页</span>
                <button
                  @click="nextPage('judge')"
                  :disabled="currentPageJudge === totalPagesJudge"
                >下一页</button>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 右边选择答题区 -->
      <transition name="slider-fade">
        <div
          class="right"
          :key="2"
        >
          <div class="title">
            <p>{{ title }}</p>
            <i class="iconfont icon-right auto-right"></i>
            <span>
              全卷共{{
                ((topic.multiQuestion && topic.multiQuestion.length) || 0) +
                ((topic.fillQuestion && topic.fillQuestion.length) || 0) +
                ((topic.judgeQuestion && topic.judgeQuestion.length) || 0)
              }}题
            </span>
          </div>
          <div class="content">
            <p class="topic">
              <span class="number">{{ number }}</span>{{ showQuestion }}
            </p>

            <!-- 单选题 -->
            <div v-if="currentType === 1">
              <el-radio-group
                v-model="radio[index]"
                @change="getChangeLabel"
              >
                <el-radio
                  :label="1"
                  :disabled="radio[index] !== undefined"
                >{{ showAnswer.answerA }}</el-radio>
                <el-radio
                  :label="2"
                  :disabled="radio[index] !== undefined"
                >{{ showAnswer.answerB }}</el-radio>
                <el-radio
                  :label="3"
                  :disabled="radio[index] !== undefined"
                >{{ showAnswer.answerC }}</el-radio>
                <el-radio
                  :label="4"
                  :disabled="radio[index] !== undefined"
                >{{ showAnswer.answerD }}</el-radio>
              </el-radio-group>

              <!-- 解析区 -->
              <div
                class="analysis"
                v-if="radio[index] !== undefined"
              >
                <ul>
                  <li>
                    <el-tag type="info">你的答案：</el-tag>
                    <span
                      class="answer-highlight"
                      :class="{
          'correct': radio[index] === getCorrectOptionIndex(reduceAnswer.rightAnswer),
          'wrong': radio[index] !== getCorrectOptionIndex(reduceAnswer.rightAnswer)
        }"
                    >
                      {{ ['','A','B','C','D'][radio[index]] }}
                    </span>
                  </li>
                  <!-- 正确答案 -->
                  <li>
                    <el-tag type="success">正确答案：</el-tag>
                    <span class="answer-highlight correct">
                      {{ reduceAnswer.rightAnswer ? reduceAnswer.rightAnswer : '未知' }}
                    </span>
                  </li>
                  <li v-if="submitTimestamp[index]">
                    <small>提交时间：{{ submitTimestamp[index] }}</small>
                  </li>
                </ul>
              </div>
            </div>

            <!-- 多选题 -->
            <div
              class="fill"
              v-if="currentType === 2"
            >
              <el-checkbox-group
                v-model="fillAnswer[index]"
                :disabled="isSubmittedFill"
              >
                <el-checkbox
                  v-for="opt in ['A','B','C','D']"
                  :key="opt"
                  :label="opt"
                >
                  {{ checkOption[`option${opt}`] }}
                </el-checkbox>
              </el-checkbox-group>

              <!-- 提交按钮 & 解析 -->
              <div
                class="submit-section"
                v-if="!isSubmittedFill"
              >
                <el-button
                  type="primary"
                  size="small"
                  @click="submitFillAnswer"
                  style="margin-top: 15px;"
                >提交答案</el-button>
              </div>
              <!-- 提交后显示答案和解析 -->
              <div
                class="analysis"
                v-if="isSubmittedFill"
              >
                <ul>
                  <!-- 你的答案 -->
                  <li>
                    <el-tag type="info">你的答案：</el-tag>
                    <span
                      class="answer-highlight"
                      :class="{
          'correct': isFillAnswerCorrect(fillAnswer[index], reduceAnswer.rightAnswer),
          'wrong': !isFillAnswerCorrect(fillAnswer[index], reduceAnswer.rightAnswer)
        }"
                    >
                      {{ fillAnswer[index].join(' ') || '未作答' }}
                    </span>
                  </li>
                  <!-- 正确答案 -->
                  <li>
                    <el-tag type="success">正确答案：</el-tag>
                    <span class="answer-highlight correct">
                      {{ reduceAnswer.rightAnswer || '未知' }}
                    </span>
                  </li>
                  <!-- 提交时间 -->
                  <li v-if="submitTimestamp[index]">
                    <small>提交时间：{{ submitTimestamp[index] }}</small>
                  </li>
                  <!-- 解析 -->
                  <li v-if="reduceAnswer.analysis">
                    {{ reduceAnswer.analysis }}
                  </li>
                  <li v-else>暂无解析</li>
                </ul>
              </div>
            </div>

            <!-- 判断题 -->
            <div
              class="judge"
              v-if="currentType === 3"
            >
              <el-radio-group
                v-model="judgeAnswer[index]"
                @change="getJudgeLabel"
              >
                <el-radio
                  :label="1"
                  :disabled="judgeAnswer[index] !== undefined"
                >正确</el-radio>
                <el-radio
                  :label="2"
                  :disabled="judgeAnswer[index] !== undefined"
                >错误</el-radio>
              </el-radio-group>

              <div
                class="analysis"
                v-if="judgeAnswer[index] !== undefined"
              >
                <ul>
                  <li>
                    <el-tag type="info">你的答案：</el-tag>
                    <span
                      class="answer-highlight"
                      :class="{
          correct: judgeAnswer[index] === (reduceAnswer.rightAnswer === '正确' ? 1 : 2),
          wrong: judgeAnswer[index] !== (reduceAnswer.rightAnswer === '正确' ? 1 : 2)
        }"
                    >
                      {{ judgeAnswer[index] === 1 ? '正确' : '错误' }}
                    </span>
                  </li>
                  <li>
                    <el-tag type="success">正确答案：</el-tag>
                    <span class="answer-highlight correct">
                      {{ reduceAnswer.rightAnswer === '正确' ? '正确' : '错误' }}
                    </span>
                  </li>
                  <li v-if="submitTimestamp[index]">
                    <small>提交时间：{{ submitTimestamp[index] }}</small>
                  </li>
                  <li v-if="reduceAnswer.analysis">{{ reduceAnswer.analysis }}</li>
                  <li v-else>暂无解析</li>
                </ul>
              </div>
            </div>
          </div>
          <div class="operation">
            <ul class="end">
              <li @click="previous()">
                <i class="iconfont icon-previous"></i>
                <span>上一题</span>
              </li>
              <li @click="mark()">
                <i class="el-icon-a-02"></i><span>标记</span>
              </li>
              <li @click="next()">
                <span>下一题</span>
                <i class="iconfont icon-next"></i>
              </li>
            </ul>

          </div>

        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      startTime: null, //考试开始时间
      endTime: null, //考试结束时间
      time: null, //考试持续时间
      reduceAnswer: [], //vue官方不支持3层以上数据嵌套,如嵌套则会数据渲染出现问题,此变量直接接收3层嵌套时的数据。
      answerScore: 0, //答题总分数
      bg_flag: false, //已答标识符,已答改变背景色
      isFillClick: false, //选择题是否点击标识符
      slider_flag: true, //左侧显示隐藏标识符
      flag: false, //个人信息显示隐藏标识符
      currentType: 1, //当前题型类型  1--选择题  2--填空题  3--判断题
      radio: [], //保存考生所有选择题的选项
      title: "请选择正确的选项",
      index: 0, //全局index
      userInfo: {
        //用户信息
        name: null,
        id: null,
      },
      topicCount: [], //每种类型题目的总数
      score: [], //每种类型分数的总数
      examData: {
        //考试信息
        // source: null,
        // totalScore: null,
      },
      //试卷信息
      topic: {
        multiQuestion: [],
        fillQuestion: [],
        judgeQuestion: [],
      },
      showQuestion: [], //当前显示题目信息
      showAnswer: {}, //当前题目对应的答案选项
      number: 1, //题号
      part: null, //填空题的空格数量
      // 存储当前点击的多选题目的选项
      checkOption: {
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
      },
      // 记录多选题是否已提交
      submittedFill: {}, // 例如: { 21: true } 表示第21题已提交
      // 当前多选题是否已提交（用于模板判断）
      isSubmittedFill: false,
      fillAnswer: {}, //保存所有多选题答案
      judgeAnswer: {}, //保存所有判断题答案
      topic1Answer: [], //学生单选选择题作答编号,
      topic2Answer: [], //学生多选选择题作答编号,
      rightAnswer: "",
      timer: "",
      paperConfig: {
        subject: "",
        multipleCount: 20,
        fillCount: 20,
        judgeCount: 20,
      },
      allQuestions: null,
      questionData: null,
      currentPageMulti: 1,
      currentPageFill: 1,
      currentPageJudge: 1,
      pageSize: 20, // 每页显示的题目数量
      currentType: 1, // 当前题型

      // 新增：记录每道题的提交时间
      submitTimestamp: {}, // 格式：{ [globalIndex]: Date.now() }

      // 新增：用于标记当前题用户选择和正确答案（供模板使用）
      userAnswer: {}, // 例如：{ 0: 1 } 单选第0题选了A；{ 21: ['A','C'] } 多选第21题
      correctAnswer: {}, // 例如：{ 0: 2, 21: ['A','B'] } 正确答案
      isAnswerVisible: {}, // 控制是否展示答案对比（提交后才显示）
    };
  },

  created() {
    this.getCookies();
    const query = this.$route.query;
    console.log("query :>> ", query);
    this.paperConfig = {
      subject: query.subject.trim(),
      multipleCount: Number(query.multipleCount) || 20,
      fillCount: Number(query.fillCount) || 20,
      judgeCount: Number(query.judgeCount) || 20,
    };
    this.getExamData();
  },
  methods: {
    //获取cookie信息
    getCookies() {
      this.userInfo.name = this.$cookies.get("cname");
      this.userInfo.id = this.$cookies.get("cid");
    },
    //获取答题数据
    getExamData() {
      let query = this.$route.query;
      console.log(`开始${query.mode === "sequence" ? "顺序" : "随机"}刷题`);
      console.log("this.paperConfig  :>> ", this.paperConfig);
      if (query.mode == "random") {
        this.generatePaper();
      } else if (query.mode === "sequence") {
        this.fetchQuestionsInOrder(); // ✅ 新增：顺序刷题
      }
    },
    //获取顺序刷题题库
    async fetchQuestionsInOrder() {
      try {
        // 1. 并行请求三种题型的题目列表
        console.log("this.paperConfig.subject :>> ", this.paperConfig.subject);

        const [multiRes, fillRes, judgeRes] = await Promise.all([
          this.$axios.get("/api/multiQuestion/sequence", {
            params: {
              subject: this.$route.query.subject,
            },
          }),
          this.$axios.get("/api/fillQuestion/sequence", {
            params: {
              subject: this.$route.query.subject,
            },
          }),
          this.$axios.get("/api/judgeQuestion/sequence", {
            params: {
              subject: this.$route.query.subject,
            },
          }),
        ]);

        // 2. 检查接口是否成功
        if (multiRes.data.code !== 200) throw new Error("单选题加载失败");
        if (fillRes.data.code !== 200) throw new Error("多选题加载失败");
        if (judgeRes.data.code !== 200) throw new Error("判断题加载失败");

        // 3. 合并所有题目，并构建 questionData（含完整信息）
        this.allQuestions = [
          ...multiRes.data.data.map((q) => ({
            ...q,
            questionType: "multiQuestion",
          })),
          ...fillRes.data.data.map((q) => ({
            ...q,
            questionType: "fillQuestion",
          })),
          ...judgeRes.data.data.map((q) => ({
            ...q,
            questionType: "judgeQuestion",
          })),
        ];

        // 4. 校验 questionId
        const invalidQuestions = this.allQuestions.filter((q) => !q.questionId);
        if (invalidQuestions.length > 0) {
          this.$message.warning(
            `缺少 questionId：${invalidQuestions
              .map((q) => q.content || q.question || "未知题")
              .join(", ")}`
          );
          return;
        }

        // 5. ✅ 构建 this.questionData：包含 questionType、questionId 和 questionDetail
        this.questionData = this.allQuestions.map((q) => ({
          questionType: q.questionType, // "multiQuestion"
          questionId: q.questionId, // 101
          questionDetail: q, // ✅ 完整题目信息（content, options, answer 等）
        }));

        // 6. 打印结构
        console.table("this.questionData=>", this.questionData);

        // 7.将questionData分类存进topic
        this.questionData.forEach((item) => {
          if (this.topic[item.questionType] !== undefined) {
            this.topic[item.questionType].push(item);
          }
        });
        console.log("按题型分类的题目:", this.topic);

        // 显示第一题
        this.index = 0;
        if (this.topic.multiQuestion.length > 0) {
          this.currentType = 1;
          this.change(0);
        } else if (this.topic.fillQuestion.length > 0) {
          this.currentType = 2;
          this.fill(0);
        } else if (this.topic.judgeQuestion.length > 0) {
          this.currentType = 3;
          this.judge(0);
        }
      } catch (error) {
        console.error("获取题目失败:", error);
        this.$message.error("加载失败，请重试");
      }
    },
    //获取随机刷题题库
    async generatePaper() {
      try {
        // 1. 并行请求三种题型的题目列表
        console.log("this.paperConfig.subject :>> ", this.paperConfig.subject);
        console.log("this.paperConfig :>> ", this.paperConfig);
        const [multiRes, fillRes, judgeRes] = await Promise.all([
          this.$axios.get("/api/multiQuestion/batch", {
            params: {
              count: this.paperConfig.multipleCount,
              subject: this.$route.query.subject,
            },
          }),
          this.$axios.get("/api/fillQuestion/batch", {
            params: {
              count: this.paperConfig.fillCount,
              subject: this.$route.query.subject,
            },
          }),
          this.$axios.get("/api/judgeQuestion/batch", {
            params: {
              count: this.paperConfig.judgeCount,
              subject: this.$route.query.subject,
            },
          }),
        ]);

        // 2. 检查接口是否成功
        if (multiRes.data.code !== 200) throw new Error("单选题加载失败");
        if (fillRes.data.code !== 200) throw new Error("多选题加载失败");
        if (judgeRes.data.code !== 200) throw new Error("判断题加载失败");

        // 3. 合并所有题目，并构建 questionData（含完整信息）
        this.allQuestions = [
          ...multiRes.data.data.map((q) => ({
            ...q,
            questionType: "multiQuestion",
          })),
          ...fillRes.data.data.map((q) => ({
            ...q,
            questionType: "fillQuestion",
          })),
          ...judgeRes.data.data.map((q) => ({
            ...q,
            questionType: "judgeQuestion",
          })),
        ];

        // 4. 校验 questionId
        const invalidQuestions = this.allQuestions.filter((q) => !q.questionId);
        if (invalidQuestions.length > 0) {
          this.$message.warning(
            `缺少 questionId：${invalidQuestions
              .map((q) => q.content || q.question || "未知题")
              .join(", ")}`
          );
          return;
        }

        // 5. ✅ 构建 this.questionData：包含 questionType、questionId 和 questionDetail
        this.questionData = this.allQuestions.map((q) => ({
          questionType: q.questionType, // "multiQuestion"
          questionId: q.questionId, // 101
          questionDetail: q, // ✅ 完整题目信息（content, options, answer 等）
        }));

        // 6. 打印结构
        console.table(this.questionData);

        // 7.将questionData分类存进topic
        this.questionData.forEach((item) => {
          if (this.topic[item.questionType] !== undefined) {
            this.topic[item.questionType].push(item);
          }
        });
        console.log("按题型分类的题目:", this.topic);

        // 显示第一题
        this.index = 0;
        if (this.topic.multiQuestion.length > 0) {
          this.currentType = 1;
          this.change(0);
        } else if (this.topic.fillQuestion.length > 0) {
          this.currentType = 2;
          this.fill(0);
        } else if (this.topic.judgeQuestion.length > 0) {
          this.currentType = 3;
          this.judge(0);
        }
      } catch (error) {
        console.error("获取题目失败:", error);
        this.$message.error("加载失败，请重试");
      }
    },
    //题目序号：下标：index
    getGlobalIndex(type, localIndex) {
      const {
        multiQuestion = [],
        fillQuestion = [],
        judgeQuestion = [],
      } = this.topic;

      switch (type) {
        case "multi":
          return (this.currentPageMulti - 1) * this.pageSize + localIndex;
        case "fill":
          return (
            multiQuestion.length +
            (this.currentPageFill - 1) * this.pageSize +
            localIndex
          );
        case "judge":
          return (
            multiQuestion.length +
            fillQuestion.length +
            (this.currentPageJudge - 1) * this.pageSize +
            localIndex
          );
        default:
          return 0;
      }
    },
    //计算局部索引的方法
    getLocalIndex(type, globalIndex) {
      const { multiQuestion = [], fillQuestion = [] } = this.topic;
      switch (type) {
        case "multi":
          return globalIndex;
        case "fill":
          return globalIndex - multiQuestion.length;
        case "judge":
          return globalIndex - multiQuestion.length - fillQuestion.length;
        default:
          return 0;
      }
    },
    // 记录提交时间与用户/正确答案
    recordAnswerAndTime(globalIndex, userAnswer, correctAnswer) {
      this.$set(
        this.submitTimestamp,
        globalIndex,
        new Date().toLocaleTimeString()
      );

      this.$set(this.userAnswer, globalIndex, userAnswer);
      this.$set(this.correctAnswer, globalIndex, correctAnswer);
      this.$set(this.isAnswerVisible, globalIndex, true);
    },
    //辅助方法：多选题提交
    submitFillAnswer() {
      const globalIndex = this.index;
      const data =
        this.topic.fillQuestion[this.getLocalIndex("fill", globalIndex)]
          .questionDetail;

      const userAnswer = this.fillAnswer[globalIndex] || [];
      const correctAnswer = data.answer ? data.answer.split("") : [];

      // ✅ 使用新名字
      const isCorrect = this.isFillAnswerCorrect(userAnswer, data.answer);

      this.recordAnswerAndTime(globalIndex, userAnswer, correctAnswer);

      this.$set(this.submittedFill, globalIndex, true);
      this.isSubmittedFill = true;

      console.log(`多选题第 ${globalIndex + 1} 题已提交，答案：`, userAnswer);
    },

    // 辅助方法：判断题目是否已提交（已作答）
    isAnswerSubmitted(type, globalIndex) {
      switch (type) {
        case "multi":
          return this.radio[globalIndex] !== undefined;
        case "fill":
          return this.submittedFill[globalIndex] === true; // 只有提交了才算“已答”
        case "judge":
          return this.judgeAnswer[globalIndex] !== undefined;
        default:
          return false;
      }
    },

    // 辅助方法：统一判断答案是否正确（独立于 this.index）
isAnswerCorrect(type, correctAnswer, userAnswer, globalIndex) {
  // 注意：我们不再依赖 this.index，而是传入 globalIndex
  switch (type) {
    case "multi":
      const correct = this.getCorrectOptionIndex(correctAnswer);
      return userAnswer === correct;

    case "fill":
      if (!userAnswer || !correctAnswer) return false;
      const userSet = new Set(Array.isArray(userAnswer) ? userAnswer : []);
      const correctSet = new Set(correctAnswer.split(""));
      if (userSet.size !== correctSet.size) return false;
      for (let ans of userSet) {
        if (!correctSet.has(ans)) return false;
      }
      return true;

    case "judge":
      const expected = correctAnswer === "正确" ? 1 : 2;
      return userAnswer === expected;

    default:
      return false;
  }
},
    // 跳转控制（分页点击）
    prevPage(type) {
      if (type === "multi" && this.currentPageMulti > 1) {
        this.currentPageMulti--;
      } else if (type === "fill" && this.currentPageFill > 1) {
        this.currentPageFill--;
      } else if (type === "judge" && this.currentPageJudge > 1) {
        this.currentPageJudge--;
      }
    },
    nextPage(type) {
      if (type === "multi" && this.currentPageMulti < this.totalPagesMulti) {
        this.currentPageMulti++;
      } else if (
        type === "fill" &&
        this.currentPageFill < this.totalPagesFill
      ) {
        this.currentPageFill++;
      } else if (
        type === "judge" &&
        this.currentPageJudge < this.totalPagesJudge
      ) {
        this.currentPageJudge++;
      }
    },
    // 新增：跳转到单选题某题
    goToMulti(index) {
      this.currentType = 1;
      this.index = index;
      this.currentPageMulti = Math.floor(index / this.pageSize) + 1;
      this.change(index); // 调用真正的 change 显示题目
    },
    // 修改：跳转到多选题某题
    goToFill(index) {
      this.currentType = 2;
      this.index = index;
      const localIndex = this.getLocalIndex("fill", index);
      this.currentPageFill = Math.floor(localIndex / this.pageSize) + 1;
      this.fill(localIndex); // 会自动同步提交状态
    },
    // 修改：跳转到判断题某题
    goToJudge(index) {
      this.currentType = 3;
      this.index = index; // 全局 index
      const localIndex = this.getLocalIndex("judge", index);
      this.currentPageJudge = Math.floor(localIndex / this.pageSize) + 1;
      this.judge(localIndex); // 传入局部索引
    },

    // 题目显示逻辑
    //单选题
    change(index) {
      const len = this.topic.multiQuestion.length;
      this.index = index; // 单选题 index 就是全局 index

      if (index >= 0 && index < len) {
        const data = this.topic.multiQuestion[index].questionDetail;
        this.reduceAnswer = data;
        this.currentType = 1;
        this.title = "请选择正确的选项";
        this.showQuestion = data.question || data.content;
        this.showAnswer = data;
        this.number = index + 1;

        if (this.radio[index]) {
          this.bg_flag = true;
        } else {
          this.bg_flag = false;
        }
      } else if (index < 0) {
        return; // 无上一题
      } else if (index >= len) {
        this.index = 0;
        this.fill(0);
      }
    },
    //多选题
    fill(index) {
      const len = this.topic.fillQuestion.length;
      const globalIndex = this.topic.multiQuestion.length + index;
      this.index = globalIndex;

      if (index >= 0 && index < len) {
        const data = this.topic.fillQuestion[index].questionDetail;
        this.reduceAnswer = data; // ✅ 添加：用于获取答案和解析
        this.showQuestion = data.question || data.content;
        this.number = this.topic.multiQuestion.length + index + 1;

        this.checkOption.optionA = data.optionA || "";
        this.checkOption.optionB = data.optionB || "";
        this.checkOption.optionC = data.optionC || "";
        this.checkOption.optionD = data.optionD || "";

        // 初始化 fillAnswer
        if (!this.fillAnswer[globalIndex]) {
          this.$set(this.fillAnswer, globalIndex, []);
        }

        // 同步提交状态
        this.isSubmittedFill = !!this.submittedFill[globalIndex];

        this.bg_flag = this.fillAnswer[globalIndex].length > 0;
      } else if (index < 0) {
        const lastIndex = this.topic.multiQuestion.length - 1;
        this.index = lastIndex;
        this.change(lastIndex);
      } else if (index >= len) {
        this.index = 0;
        this.judge(0);
      }
    },
    //判断题
    judge(index) {
      const data = this.topic.judgeQuestion[index].questionDetail;
      this.reduceAnswer = data;

      const len = this.topic.judgeQuestion.length;
      const globalIndex =
        this.topic.multiQuestion.length +
        this.topic.fillQuestion.length +
        index;
      this.index = globalIndex; // 保存全局 index

      if (index >= 0 && index < len) {
        const data = this.topic.judgeQuestion[index].questionDetail;
        this.showQuestion = data.question || data.content;
        this.number = globalIndex + 1;

        //
        this.bg_flag = this.judgeAnswer.hasOwnProperty(globalIndex);
      } else if (index < 0) {
        // 上一题越界：跳到上一题型（多选）最后一题
        const lastIndex = this.topic.fillQuestion.length - 1;
        this.index = this.topic.multiQuestion.length + lastIndex;
        this.fill(lastIndex);
      } else if (index >= len) {
        // 下一题越界：跳回第一题
        this.index = 0;
        this.change(0);
      }
    },

    // 答题逻辑
    //获取选择题作答选项
    getChangeLabel(val) {
      this.radio[this.index] = val;

      const data = this.topic.multiQuestion[this.index].questionDetail;
      const correct = this.getCorrectOptionIndex(data.answer); // 假设 answer 是 1~4 或 'A'~'D'

      this.recordAnswerAndTime(this.index, val, correct);
      this.radio[this.index] = val; //当前选择的序号
      if (val) {
        let data = this.topic.multiQuestion;
        this.bg_flag = true;
        data[this.index]["isClick"] = true;
      }
      /* 保存学生答题选项 */
      this.topic1Answer[this.index] = val;
      if (val) {
        this.bg_flag = true;
        this.topic.multiQuestion[this.index]["isClick"] = true;
      }
      this.topic1Answer[this.index] = val;
    },
    //辅助单项选择题将abcd转为1234
    getCorrectOptionIndex(answer) {
      if (typeof answer === "number") return answer;

      // 统一处理字符串，支持 'A' 或 '1'
      const str = String(answer).trim().toUpperCase();
      const map = { A: 1, B: 2, C: 3, D: 4, 1: 1, 2: 2, 3: 3, 4: 4 };
      return map[str] || 0;
    },
    //获取多选题作答选项
    getChangeCheckLabel(val) {
      const globalIndex = this.index - this.topic.multiQuestion.length;
      console.log("globalIndex :>> ", globalIndex);
      this.$set(this.fillAnswer, globalIndex, val);

      if (val && val.length > 0) {
        this.bg_flag = true;
        this.index;
        this.topic.fillQuestion[globalIndex]["isClick"] = true;
      }

      this.topic2Answer[this.index] = [...val].sort(); // 避免修改原数组
    },
    //获取判断题作答选项
    getJudgeLabel(val) {
      const globalIndex = this.index;
      const allQuestions = [
        ...(this.topic.multiQuestion || []),
        ...(this.topic.fillQuestion || []),
        ...(this.topic.judgeQuestion || []),
      ];

      console.log(this.index);
      console.table(this.reduceAnswer);

      const correct = allQuestions[globalIndex]
        ? allQuestions[globalIndex].answer === "T"
          ? 1
          : 2
        : null;

      this.recordAnswerAndTime(globalIndex, val, correct);

      this.$set(this.judgeAnswer, globalIndex, val);

      this.bg_flag = true;
      let judegIndex =
        globalIndex -
        this.topic.multiQuestion.length -
        this.topic.fillQuestion.length;
      this.topic.judgeQuestion[judegIndex]["isClick"] = true;
    },

    // 判断多选题答案是否正确
    isFillAnswerCorrect(userAnswerArray, correctAnswerStr) {
      if (!userAnswerArray || !correctAnswerStr) return false;
      const userSet = new Set(userAnswerArray);
      const correctSet = new Set(correctAnswerStr.split(""));
      if (userSet.size !== correctSet.size) return false;
      for (let ans of userSet) {
        if (!correctSet.has(ans)) return false;
      }
      return true;
    },

    // 上一题 / 下一题
    previous() {
      this.index--;
      if (this.index < 0) {
        this.index = 0;
        return;
      }

      const multiLen = this.topic.multiQuestion.length;
      const fillLen = this.topic.fillQuestion.length;
      const judgeLen = this.topic.judgeQuestion.length;

      if (this.index < multiLen) {
        this.currentType = 1;
        this.change(this.index);
      } else if (this.index < multiLen + fillLen) {
        this.currentType = 2;
        const localIndex = this.index - multiLen;
        this.fill(localIndex);
      } else {
        this.currentType = 3;
        const localIndex = this.index - multiLen - fillLen;
        this.judge(localIndex);
      }
    },
    next() {
      const multiLen = this.topic.multiQuestion.length;
      const fillLen = this.topic.fillQuestion.length;
      const judgeLen = this.topic.judgeQuestion.length;

      this.index++;

      if (this.index >= multiLen + fillLen + judgeLen) {
        this.index = multiLen + fillLen + judgeLen - 1;
        return;
      }

      if (this.index < multiLen) {
        this.currentType = 1;
        this.change(this.index);
      } else if (this.index < multiLen + fillLen) {
        this.currentType = 2;
        const localIndex = this.index - multiLen;
        this.fill(localIndex);
      } else {
        this.currentType = 3;
        const localIndex = this.index - multiLen - fillLen;
        this.judge(localIndex);
      }
    },
    //标记功能
    mark() {
      switch (this.currentType) {
        case 1:
          this.topic.multiQuestion[this.index]["isMark"] = true; //选择题标记
          break;
        case 2:
          this.topic.fillQuestion[this.index]["isMark"] = true; //填空题标记
          break;
        case 3:
          this.topic.judgeQuestion[this.index]["isMark"] = true; //判断题标记
      }
    },
  },
  computed: {
    paginatedMulti() {
      const start = (this.currentPageMulti - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.topic.multiQuestion.slice(start, end);
    },
    paginatedFill() {
      const start = (this.currentPageFill - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.topic.fillQuestion.slice(start, end);
    },
    paginatedJudge() {
      const start = (this.currentPageJudge - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.topic.judgeQuestion.slice(start, end);
    },
    totalPagesMulti() {
      return Math.ceil((this.topic.multiQuestion || []).length / this.pageSize);
    },
    totalPagesFill() {
      return Math.ceil((this.topic.fillQuestion || []).length / this.pageSize);
    },
    totalPagesJudge() {
      return Math.ceil((this.topic.judgeQuestion || []).length / this.pageSize);
    },
    getCorrectAnswerLabels() {
      const answer = this.reduceAnswer.answer; // 假设后端返回的是 "ABC" 字符串
      if (!answer) return "";
      return answer.split("").join(", "); // "ABC" => "A, B, C"
    },
  },
};
</script>

<style lang="less">
.iconfont.icon-time {
  color: CornflowerBlue;
  margin: 0px 6px 0px 20px;
}
.analysis {
  margin-top: 20px;
  .right {
    color: #2776df;
    font-size: 18px;
    border: 1px solid #2776df;
    padding: 0px 6px;
    border-radius: 4px;
    margin-left: 20px;
  }
  ul li:nth-child(2) {
    margin: 20px 0px;
  }
  ul li:nth-child(3) {
    padding: 10px;
    background-color: #d3c6c9;
    border-radius: 4px;
  }
}
.analysis span:nth-child(1) {
  font-size: 18px;
}
.mark {
  position: absolute;
  width: 4px;
  height: 4px;
  content: "";
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 22px;
}
.border {
  position: relative;
  border: 1px solid #ff90aa !important;
}
.bg {
  background-color: #5188b8 !important;
}
.fill .el-input {
  display: inline-flex;
  width: 150px;
  margin-left: 20px;
  .el-input__inner {
    border: 1px solid transparent;
    border-bottom: 1px solid #eee;
    padding-left: 20px;
  }
}
/* slider过渡效果 */
.slider-fade-enter-active {
  transition: all 0.3s ease;
}
.slider-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}
.slider-fade-enter,
.slider-fade-leave-to {
  transform: translateX(-100px);
  opacity: 0;
}
.operation .end li:nth-child(2) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: CornflowerBlue;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  color: #fff;
}
.operation .end li {
  cursor: pointer;
  margin: 0 100px;
}
.operation {
  background-color: #fff;
  border-radius: 4px;
  padding: 10px 0px;
  margin-right: 10px;
}
.operation .end {
  display: flex;
  justify-content: center;
  align-items: center;
  color: CornflowerBlue;
}
.content .number {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: CornflowerBlue;
  border-radius: 4px;
  margin-right: 4px;
}
.content {
  padding: 0px 20px;
}
.content .topic {
  padding: 20px 0px;
  padding-top: 30px;
}
.right .content {
  background-color: #fff;
  margin: 10px;
  margin-left: 0px;
  height: 470px;
}
.content .el-radio-group label {
  color: #000;
  margin: 5px 0px;
}
.content .el-radio-group {
  display: flex;
  flex-direction: column;
}
.content .el-checkbox-group label {
  color: #000;
  margin: 5px 0px;
}
.content .el-checkbox-group {
  display: flex;
  flex-direction: column;
}
.right .title p {
  margin-left: 20px;
}
.flexarea {
  display: flex;
}
.flexarea .right {
  flex: 1;
}
.auto-right {
  margin-left: auto;
  color: #2776df;
  margin-right: 10px;
}
.right .title {
  margin-right: 10px;
  padding-right: 30px;
  display: flex;
  margin-top: 10px;
  background-color: #fff;
  height: 50px;
  line-height: 50px;
}
.clearfix {
  clear: both;
}
.l-bottom .final {
  cursor: pointer;
  display: inline-block;
  text-align: center;
  background-color: CornflowerBlue;
  width: 240px;
  margin: 20px 0px 20px 10px;
  border-radius: 4px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  margin-top: 22px;
}
#answer .left .item {
  padding: 0px;
  font-size: 16px;
}
.l-bottom {
  border-radius: 4px;
  background-color: #fff;
}
.l-bottom .item p {
  margin-bottom: 15px;
  margin-top: 10px;
  color: #000;
  margin-left: 10px;
  letter-spacing: 2px;
}
.l-bottom .item li {
  width: 15%;
  margin-left: 5px;
  margin-bottom: 10px;
}
.l-bottom .item {
  display: flex;
  flex-direction: column;
}
.l-bottom .item ul {
  width: 100%;
  margin-bottom: -8px;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.l-bottom .item ul li a {
  position: relative;
  justify-content: center;
  display: inline-flex;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #eee;
  text-align: center;
  color: #000;
  font-size: 16px;
}
.left .l-top {
  display: flex;
  justify-content: space-around;
  padding: 16px 0px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #fff;
}
.left {
  width: 260px;
  height: 100%;
  margin: 10px 10px 0px 10px;
}
.left .l-top li:nth-child(2) a {
  border: 1px solid #eee;
}
.left .l-top li:nth-child(3) a {
  background-color: #5188b8;
  border: none;
}
.left .l-top li:nth-child(4) a {
  position: relative;
  border: 1px solid #eee;
}
.left .l-top li:nth-child(4) a::before {
  width: 4px;
  height: 4px;
  content: " ";
  position: absolute;
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 16px;
}
.left .l-top li {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.left .l-top li a {
  display: inline-block;
  padding: 10px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #ff90aa;
}
#answer .top {
  background-color: CornflowerBlue;
}
#answer .item {
  color: #fff;
  display: flex;
  padding: 20px;
  font-size: 20px;
}
#answer .top .item li:nth-child(1) {
  margin-right: 10px;
}
#answer .top .item li:nth-child(3) {
  position: relative;
  margin-left: auto;
}
#answer {
  padding-bottom: 30px;
}
.icon20 {
  font-size: 20px;
  font-weight: bold;
}
.item .msg {
  padding: 10px 15px;
  border-radius: 4px;
  top: 47px;
  right: -30px;
  color: #6c757d;
  position: absolute;
  border: 1px solid rgba(0, 0, 0, 0.15);
  background-color: #fff;
}
.item .msg p {
  font-size: 16px;
  width: 200px;
  text-align: left;
}

.pagination {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中（可选） */
  gap: 10px; /* 按钮之间的间距 */
  margin-top: 10px; /* 可选：与上面内容的间距 */
  text-align: center; /* 兼容性备用 */
}

.section-title {
  text-align: center; /* 水平居中 */
  font-weight: bold; /* 加粗 */
  background-color: #1e90ff; /* 蓝色底色，例如 DodgerBlue */
  color: white; /* 建议白色文字，提升可读性 */
  padding: 10px 0; /* 上下内边距，让横幅更明显 */
  margin: 0; /* 可选：去除默认外边距 */
  border-radius: 4px; /* 可选：圆角，更美观 */
}

.submit-section {
  margin-top: 15px;
}

.analysis {
  margin-top: 20px;
  ul li {
    margin: 10px 0;
  }
  .right {
    color: #2776df;
    font-size: 18px;
    border: 1px solid #2776df;
    padding: 0 6px;
    border-radius: 4px;
    margin-left: 20px;
  }
}
.answer-highlight {
  padding: 2px 8px;
  margin: 0 8px;
  border-radius: 4px;
  font-weight: bold;
}

.answer-highlight.correct {
  background-color: #a5d8a5;
  color: #155724;
}

.answer-highlight.wrong {
  background-color: #f5c6cb;
  color: #721c24;
}

/* 左侧题号：正确为绿色，错误为红色 */
.l-bottom .item ul li a.correct {
  background-color: #4caf50 !important; /* 绿色 */
  color: white !important;
  border-color: #4caf50 !important;
}
.l-bottom .item ul li a.wrong {
  background-color: #f44336 !important; /* 红色 */
  color: white !important;
  border-color: #f44336 !important;
}
</style>